//封装购物车模块
import { computed, ref } from "vue";
import { defineStore } from "pinia";
import { useUserStore } from "./userStore";
import { insertCartAPI, findNewCartListAPI } from "@/apis/cart";
import { delCartAPI } from "@/apis/cart";

export const useCartStore = defineStore('cart', () => {
    const userStore = useUserStore()
    const isLogin = computed(() => userStore.userInfo.token)
    //定义state操作-cartList
    const cartList = ref([])

    //获取最新购物车列表action
    const upadteNewlist = async () => {
        const res = await findNewCartListAPI()
        cartList.value = res.result
    }

    //定义action操作-addCart
    const addCart = async (goods) => {
        const { skuId, count } = goods
        if (isLogin.value) {
            //登录后的加入购物车逻辑
            await insertCartAPI({ skuId, count })
            upadteNewlist()

        } else {
            //添加购物车操作
            //已添加过-count+1
            //没有添加过 - 直接push
            //思路：通过匹配传递过来的商品对象skuId能不能在cartList找到，找到就是添加了
            const item = cartList.value.find((item) => goods.skuId === item.skuId)
            if (item) {
                //找到了
                item.count++
            } else {
                //没找到
                cartList.value.push(goods)
            }

        }

    }
    //删除购物车
    const delCart = async (skuId) => {
        if (isLogin.value) {
            //调用接口实现接口购物车中的删除功能
            await delCartAPI([skuId])
            upadteNewlist()
        } else {
            //思路：
            //1.找到要删除项的下标，splice
            const idx = cartList.value.findIndex((item) => skuId === item.skuId)
            cartList.value.splice(idx, 1)
            //2.使用数组过滤，filter

        }
    }
    //清除购物车
    const clearCart = () => {
        cartList.value = []
    }

    //单选功能
    const singleCheck = (skuId, selected) => {
        const item = cartList.value.find((item) => item.skuId === skuId)
        item.selected = selected
    }
    //计算属性
    //1.总的数量，所有count和
    const allCount = computed(() => cartList.value.reduce((a, c) => a + c.count, 0))
    //2.总价，所有项count*price之和
    const allPrice = computed(() => cartList.value.reduce((a, c) => a + c.count * c.price, 0))
    //3.已选择数量
    const selectedCount = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count, 0))
    //4.已选择商品价格合计
    const selectedPrice = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count * c.price, 0))
    //是否全选
    const isAll = computed(() => cartList.value.every((item) => item.selected))
    //全选功能
    const allCheck = (selected) => {
        //把cartlist中的每项selected都设置为当前的全选框状态
        cartList.value.forEach(item => item.selected = selected)
    }
    return {
        cartList,
        addCart,
        delCart,
        allCount,
        allPrice,
        clearCart,
        singleCheck,
        isAll,
        allCheck,
        selectedCount,
        selectedPrice,
        upadteNewlist,
    }
}, {
    persist: true,
},)